<template>
  <BackTab>
    <template v-slot:center>失联信息管理中心___</template>
    <template v-slot:icon
      ><el-icon><UserFilled /></el-icon
    ></template>
    <template v-slot:list>失联者列表</template>
  </BackTab>

  <el-card class="box-card">
    <div class="common-layout">
      <el-container>
        <el-header>
          <div class="search">
            <div class="name">用户名:</div>
            <el-input
              v-model="input"
              placeholder="输入搜索姓名"
              :suffix-icon="Search"
            />
            <el-button type="primary" class="seaBtn" @click="searchLoser"
              >搜索</el-button
            >
            <el-button type="primary" @click="getAllLoser">全部用户</el-button>
          </div>
          <div class="btnBox">
            <el-button type="primary" @click="addVisible = true"
              >添加用户</el-button
            >
          </div>
        </el-header>
        <el-main>
          <el-table :data="loserList" stripe border style="width: 100%">
            <el-table-column label="#" type="expand">
              <template #default="props" class="linkmanList">
                <el-table :data="props.row.linkmans" stripe border>
                  <el-table-column
                    label="联系人姓名"
                    prop="m_name"
                    width="120px"
                  />
                  <el-table-column label="手机号" prop="m_phone" />
                  <el-table-column label="邮箱" prop="m_email" />
                  <el-table-column label="微信" prop="m_wechat" />
                  <el-table-column label="居住地" prop="m_addr" />
                  <el-table-column
                    label="关系"
                    prop="m_relat_l"
                    width="120px"
                  />
                  <el-table-column label="操作">
                    <template #default="scope">
                      <el-button
                        size="small"
                        type="primary"
                        @click="editLinkman(scope.row.id)"
                        >修改</el-button
                      >
                      <el-button
                        size="small"
                        type="danger"
                        @click="deleteLinkman(scope.row.id)"
                        >删除</el-button
                      >
                    </template>
                  </el-table-column>
                </el-table>
              </template>
            </el-table-column>
            <el-table-column prop="l_name" label="姓名" width="110px" />
            <el-table-column prop="l_sex" label="性别" width="100px" />
            <el-table-column prop="l_birth_date" label="出生日期" width="130px">
              <template #default="scope">
                <span>{{ utils.ymd(scope.row.l_birth_date) }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="l_miss_date" label="失踪时间" width="130px">
              <template #default="scope">
                {{ utils.ymd(scope.row.l_miss_date) }}
              </template>
            </el-table-column>
            <el-table-column prop="l_miss_addr" label="失踪地点" />
            <el-table-column prop="l_type" label="失踪类型" width="120px" />
            <el-table-column label="操作" width="320px">
              <template #default="scope">
                <el-button
                  size="small"
                  type="info"
                  @click="detailsLoser(scope.row.id)"
                  >详情</el-button
                >
                <el-button
                  size="small"
                  type="primary"
                  @click="editDialog(scope.row.id)"
                  >更换头像</el-button
                >
                <el-button
                  size="small"
                  type="primary"
                  @click="addLinkman(scope.row.id)"
                  >添加联系人</el-button
                >
                <el-button
                  size="small"
                  type="danger"
                  @click="deleteLoserOne(scope.row.id)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
          <div class="page">
            <el-pagination
              layout="total,prev, pager, next, jumper"
              :total="total"
              @current-change="handleCurrentChange"
            />
          </div>
        </el-main>
      </el-container>
    </div>
  </el-card>

  <!-- 详情 -->
  <el-dialog
    v-model="deltailVisible"
    title="失联者信息详情"
    class="detail"
    width="30%"
  >
    <div class="detailInfos">
      <div class="top">
        <img class="img" :src="singerLoser.l_photos" alt="" />
      </div>
      <div class="bottom">
        <div class="item">
          <div class="label">姓名：</div>
          <div class="data">{{ singerLoser.l_name }}</div>
        </div>
        <div class="item">
          <div class="label">性别：</div>
          <div class="data">{{ singerLoser.l_sex }}</div>
        </div>
        <div class="item">
          <div class="label">年龄：</div>
          <div class="data">{{ age }}</div>
        </div>
        <div class="item">
          <div class="label">出生地址：</div>
          <div class="data">{{ singerLoser.l_birth_addr }}</div>
        </div>
        <div class="item">
          <div class="label">失踪日期：</div>
          <div class="data">{{ utils.ymd(singerLoser.l_miss_date) }}</div>
        </div>
        <div class="item">
          <div class="label">失踪地址：</div>
          <div class="data">{{ singerLoser.l_miss_addr }}</div>
        </div>
        <div class="item">
          <div class="label">失踪类型：</div>
          <div class="data">{{ singerLoser.l_type }}</div>
        </div>
        <div class="item">
          <div class="label">特征描述：</div>
          <div class="data">{{ singerLoser.l_descript }}</div>
        </div>
      </div>
    </div>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="deltailVisible = false" type="primary"
          >确定</el-button
        >
      </span>
    </template>
  </el-dialog>

  <!-- 添加 -->
  <el-dialog v-model="addVisible" title="失联人登记" width="60%" center>
    <div class="addLoser">
      <div class="images">
        <el-upload
          class="avatar-uploader"
          action=""
          :http-request="handleLoser"
          :show-file-list="false"
        >
          <img v-if="LoserImage" :src="LoserImage" class="avatar" />
          <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
        </el-upload>
      </div>
      <div class="loserInfo">
        <Loser :LoserUrl="LoserUrl" @on-link="changeFlag"></Loser>
      </div>
    </div>
  </el-dialog>

  <!-- 修改 -->
  <el-dialog v-model="editVisible" title="用户信息" width="30%" center>
    <div class="updateImg">
      <el-upload
        class="avatar-uploader"
        action=""
        :http-request="handleRequest"
        :show-file-list="false"
      >
        <img v-if="imageUrl" :src="imageUrl" class="avatar" />
        <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
      </el-upload>
    </div>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="editeImg" type="primary">确定</el-button>
      </span>
    </template>
  </el-dialog>

  <!-- 单独添加联系人 -->
  <el-dialog v-model="addLinkVisible" title="添加联系人" width="30%" center>
    <Linkman :loserId="loserId" @on-click="getUpdate" />
  </el-dialog>

  <!-- 修改联系人窗口 -->
  <el-dialog v-model="editlinkVisible" title="用户信息" width="30%" center>
    <el-form
      :model="linkInfo"
      :rules="LinkRules"
      ref="LinkFormRef"
      label-width="120px"
    >
      <el-form-item label="手机号" prop="m_phone">
        <el-input v-model="linkInfo.m_phone" />
      </el-form-item>
      <el-form-item label="邮箱" prop="m_email">
        <el-input v-model="linkInfo.m_email" />
      </el-form-item>
      <el-form-item label="微信" prop="m_wechat">
        <el-input v-model="linkInfo.m_wechat" />
      </el-form-item>
      <el-form-item label="居住地址" prop="m_addr">
        <el-input v-model="linkInfo.m_addr" />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="editlinkVisible = false">取消</el-button>
        <el-button type="primary" @click="submitLinkUpdate(LinkFormRef)"
          >确定</el-button
        >
      </span>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { getCurrentInstance, onMounted, provide, ref } from "vue";
import BackTab from "@/components/common/tabbar/BackTab.vue";
import {
  getLoser,
  getSearchLoser,
  getDetail,
  getAllLosers,
  query,
} from "@/server/loser";
import { getLinkInfo } from "@/server/linkman";
import utils from "@/utils/utils";
import { Search } from "@element-plus/icons-vue";
import Loser from "@/components/common/RgisterTable/Loser.vue";
import Linkman from "@/components/common/RgisterTable/Linkman.vue";
import { ElMessage, type FormInstance } from "element-plus";
import { useLoserRegist } from "@/hooks/loginForm/loserRegist";
const {
  addVisible,
  LinkFormRef,
  LinkRules,
  LoserImage,
  LoserUrl,
  handleLoser,
} = useLoserRegist();
const { proxy }: any = getCurrentInstance();

const loserList = ref<any>([]);
const input = ref("");
const deltailVisible = ref(false);
// 修改
const editVisible = ref(false);
// 单个用户信息
const singerLoser = ref<any>([]);
const singerId = ref(0);
const age = ref(0);
// 添加联系人窗口
let addLinkVisible = ref(false);
provide("addLinkVisible", addLinkVisible);
//单个loser的id
const loserId = ref(0);
const editlinkVisible = ref(false);
const linkInfo = ref<any>([]);
const total = ref(0);
const noPass = ref<any>([]);

const handleCurrentChange = async (newPage: number) => {
  query.page = newPage;
  await getLoserList();
};

onMounted(async () => {
  await getLoserList();
});
function getLoserList() {
  getLoser().then(async (res1: any) => {
    loserList.value = res1.data.filter((item: any) => item.state == 1);
    await getAllLosers().then((res2: any) => {
      noPass.value = res2.data.filter((item: any) => item.state != 1);
      total.value = res1.total - noPass.value.length
    });
  });
}

const searchLoser = () => {
  if (input.value.trim() == "") return (input.value = "");
  getSearchLoser(input.value).then((res: any) => {
    loserList.value = res.data;
  });
};
const getAllLoser = async () => {
  await getLoserList();
  input.value = "";
};
//查看详情
const detailsLoser = (id: number) => {
  deltailVisible.value = true;
  getDetail(id).then((res: any) => {
    singerLoser.value = res;
    age.value = utils.fillAge(JSON.stringify(res.l_birth_date));
  });
};
//修改个人头像
//渲染页面的url
const imageUrl = ref("");
//用于存储数据库的url
const saveUrl = ref("");
const handleRequest = (e: any) => {
  const fd = new FileReader();
  fd.readAsDataURL(e.file);
  imageUrl.value = URL.createObjectURL(e.file);
  saveUrl.value = "https://img2.baidu.com/it/" + e.file.name.slice(0, -5);
};
const editDialog = (id: number) => {
  singerId.value = id;
  editVisible.value = true;
};

// 修改头像
const editeImg = () => {
  if (!imageUrl.value) {
    ElMessage.error("头像更换失败");
  } else {
    proxy.$http
      .post("/loser/update/" + singerId.value, {
        l_photos: saveUrl.value,
      })
      .then((res: any) => {
        ElMessage.success(res.message);
      });
  }
  editVisible.value = false;
};
//删除
const deleteLoserOne = (id: number) => {
  proxy.$http
    .get("/loser/del/" + id)
    .then(async (res: any) => {
      ElMessage.success(res.message);
      await getLoserList();
    })
    .catch((err: any) => {
      if (err.code == "ERR_BAD_RESPONSE") {
        ElMessage.error("删除失败，请删除相关联系人后重试");
      }
    });
};

//联系人列表
const addLinkman = (id: any) => {
  loserId.value = id;
  addLinkVisible.value = true;
};
const editLinkman = (id: number) => {
  editlinkVisible.value = true;
  getLinkInfo(id).then((res: any) => {
    linkInfo.value = res;
  });
};
const deleteLinkman = (id: any) => {
  proxy.$http.post("/linkmans/del/" + id).then(async (res: any) => {
    ElMessage.success(res);
    await getLoserList();
  });
};
//添加联系人窗口
const getUpdate = async () => {
  await getLoserList();
  addLinkVisible.value = false;
};
//修改lInk提交按钮
const submitLinkUpdate = async (updateInfo: FormInstance | undefined) => {
  if (!updateInfo) return;
  await updateInfo.validate((valid) => {
    if (!valid) return;
    proxy.$http
      .post("/linkmans/update/" + linkInfo.value.id, linkInfo.value)
      .then(async (res: any) => {
        ElMessage.success(res.message);
        await getLoserList();
        editlinkVisible.value = false;
      });
  });
};

const changeFlag = async () => {
  addVisible.value = false;
  await getLoserList();
};
</script>

<style scoped lang="less">
.common-layout {
  padding: 0;
  .el-container {
    .el-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      // background-color: pink;
      border: 1px solid #ebeef5;
      padding: 10px;
      .search {
        display: flex;
        align-items: center;
        .name {
          width: 100px;
          font-weight: bolder;
        }
        .seaBtn {
          margin-left: 5px;
        }
      }
    }
    .el-main {
      padding: 0;
      .page {
        padding-top: 10px;
        display: flex;
        justify-content: end;
      }
    }
  }
}

.detail {
  .detailInfos {
    display: flex;
    flex-direction: column;
    .top {
      width: 100px;
      height: 120px;
      .img {
        width: 100%;
        height: 100%;
      }
    }
    .bottom {
      margin-top: 15px;
      .item {
        display: flex;
        margin-bottom: 8px;
        .label {
          font-weight: bolder;
          padding-right: 8px;
        }
      }
    }
  }
}

.addLoser {
  display: grid;
  grid-template-columns: 40% 60%;
  .images {
    padding: 0 10px 0 0;
    display: flex;
    justify-content: center;
    .avatar-uploader {
      width: 250px;
      height: 300px;
      display: flex;
      align-items: center;
      justify-content: center;
      border: 1px dotted gray;

      .avatar {
        width: 100%;
        height: 300px;
      }
    }
  }
  .linkmanInfo {
    padding: 0 10px;
    .submit {
      display: flex;
      justify-content: end;
      padding: 20px 0 10px 0;
    }
  }
}

.updateImg {
  // background-color: red;
  padding: 0 10px 0 0;
  display: flex;
  justify-content: center;
  .avatar-uploader {
    width: 250px;
    height: 300px;
    display: flex;
    align-items: center;
    justify-content: center;
    border: 1px dotted gray;

    .avatar {
      width: 100%;
      height: 300px;
    }
  }
}
</style>
